import { _decorator, Component, Node } from 'cc';
import { ToggleController } from './ToggleController';
const { ccclass, property } = _decorator;

@ccclass('ToggleGroupController')
export class ToggleGroupController extends Component {

    @property(Number)
    private curToggleIndex: number = 0;

    curToggleKey: string;
    toggleControllerList: Array<ToggleController> = [];
    callback: Function;

    start() {
        for (let index = 0; index < this.node.children.length; index++) {
            const element = this.node.children[index];
            let controller = element.getComponent(ToggleController);
            controller.Init(element.name, this);
            this.toggleControllerList.push(controller);
            if (this.curToggleIndex == index) {
                this.curToggleKey = element.name;
            }
        }

        this.UpdateToggle();
    }

    OnToggleGroup(key) {
        this.curToggleKey = key;
        // for (let index = 0; index < this.toggleControllerList.length; index++) {
        //     const element = this.toggleControllerList[index];
        //     if (element.node.name == key) {
        //         this.curToggleIndex = index;
        //         break;
        //     }
        // }
        this.UpdateToggle();
    }

    UpdateToggle() {
        for (let index = 0; index < this.toggleControllerList.length; index++) {
            const element = this.toggleControllerList[index];
            if (element.node.name == this.curToggleKey) {
                this.curToggleIndex = index;
                element.OnUpdateSelect(true);
                if (this.callback) {
                    this.callback(this.curToggleIndex);
                }
            }
            else {
                element.OnUpdateSelect(false);
            }
        }
    }

    ResetToggleNone()
    {
        this.curToggleKey = "";
        this.UpdateToggle();
    }


}

